<template>
  <el-card>
    <div class="flex justify-between items-center mb-4">
      <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
      <el-tooltip effect="dark" content="刷新" placement="bottom">
        <el-button text @click="getData"><el-icon size="20">
            <RefreshRight />
          </el-icon></el-button>
      </el-tooltip>
    </div>

    <el-table :data="tableData" v-loading="loading">
      <el-table-column label="序號">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="分類名稱" />
      <el-table-column label="分類圖">
        <template #default="{ row }">
          
          <el-image style="width: 100px; height: 50px" :src="row.url.toString().split(',')[0]" hide-on-click-modal
            :preview-src-list="[row.url.toString().split(',')[0]]" :preview-teleported="true" />
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="創建時間" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleUpdate(scope.row)">修改</el-button>

          <el-popconfirm title="是否要刪除該分類？" width="180" confirmButtonText="確認" cancelButtonText="取消"
            @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <FormDrawer ref="drawerRef" :title="title" @submit="onSubmit" destroyOnClose>
      <el-form :model="form" :rules="formRules" ref="formRef">
        <el-form-item class="pt-5" prop="name" label="分類名稱">
          <el-input v-model="form.name" placeholder="分類名稱" />
        </el-form-item>
        <el-form-item label="圖片上傳" prop="url">

          <UploadImage :imgUrl="form.url" @getUrl="getIdCardFrontUrl" :limit="1"></UploadImage>
        </el-form-item>
      </el-form>
    </FormDrawer>
  </el-card>
</template>

<script setup>

import { ref, computed } from 'vue'
import { getList, create, update, del } from '@/api/category.js'
import FormDrawer from '@/components/FormDrawer.vue';
import { msg } from '@/composables/util.js'
import UploadImage from '@/components/UploadImage.vue'
const tableData = ref([])
const drawerRef = ref(null)
const formRef = ref(null)
const form = ref({ name: "", url: [] })
const loading = ref(false)
const formRules = ref({
  name: [{ required: true, message: '分類名稱不能為空', trigger: 'blur' },],
  url: [{required: true,message: '圖片不能為空',trigger: 'blur'}]
})
const getData = () => {
  loading.value = true
  getList().then(res => {
    tableData.value = res
  }).finally(() => {
    loading.value = false
  })
}
getData()

const editid = ref(0)
const title = computed(() => editid.value ? "修改" : "新增")


const handleCreate = () => {
  editid.value = 0
  resetForm({
    name: "",
    url: []
  })
  drawerRef.value.open()
}

const onSubmit = () => {
  formRef.value.validate(valid => {
    if (!valid) return

    let fun = editid.value ? update(editid.value, form.value) : create(form.value)

    drawerRef.value.showLoading()
    fun.then(res => {
      msg(title.value + '成功')
      getData()
      drawerRef.value.close()

    }).finally(() => {
      drawerRef.value.closeLoading()
    })
  })

}

//重置表單
const resetForm = (row) => {
  for (let key in form.value) {
    form.value[key] = row[key]
  }
}

const handleUpdate = (row) => {
  editid.value = row.id

  resetForm(row)
  drawerRef.value.open()
}

const handleDelete = (id) => {
  loading.value = true
  del({ "id": id }).then(res => {
    msg('刪除成功')
    getData()
  }).finally(() => {
    loading.value = false
  })
}
const getIdCardFrontUrl = (url) => {

  form.value.url = url;
};


</script>

